package com.simba.server.task;

import java.util.ArrayList;
import java.util.List;

import com.simba.server.commands.impl.fetch.FetchPacketOffByNoSyncCmd;
import com.simba.server.commands.impl.fetch.FetchSlotPackByNoSyncCmd;
import com.simba.server.commands.impl.record.RecordPacketOffHistoryCmd;
import com.simba.server.commands.impl.record.RecordSlotPackHistoryCmd;
import com.simba.server.commands.impl.update.RenewPacketOffSyncCmd;
import com.simba.server.commands.impl.update.RenewSlotPackSyncCmd;
import com.simba.server.components.CommandExecutor;
import org.apache.log4j.Logger;


import com.simba.common.log.LogUtil;

import com.simba.server.components.SorterParams;

public class DataSyncTask extends Thread
{
	private final static Logger logger = Logger.getLogger(DataSyncTask.class);
	private static final int SYNC_INTERVAL = 60 * 1000;
	private final List<Integer> idList = new ArrayList<>();

	public DataSyncTask()
	{
		this.setName("Data-Sync-Task");
	}

	@Override
	public void run()
	{
		while (!Thread.currentThread().isInterrupted())
		{
			try
			{
				this.syncDataToHistory();
				Thread.sleep(
						SorterParams.getInstance().getSyncDataTime() * DataSyncTask.SYNC_INTERVAL);
			}
			catch (Exception ex)
			{
				if (ex instanceof InterruptedException)
				{
					Thread.currentThread().interrupt();
				}
				LogUtil.LogError(DataSyncTask.logger,
						"Catch an exception [" + ex.getMessage() + "]");
			}
		}
	}

	private void doSyncData()
	{
		this.syncPackageOffData();
		this.syncSlotPackData();
	}

	private void syncDataToHistory()
	{
		try
		{
			this.doSyncData();
		}
		catch (Exception ex)
		{
			LogUtil.LogError(DataSyncTask.logger,
					"[syncDataToHistory] : Catch an exception [" + ex.getMessage() + "]");
		}
	}

	private void syncSlotPackData()
	{
		idList.clear();
		boolean flag = CommandExecutor.executorSqlCommand(FetchSlotPackByNoSyncCmd.NAME, idList,false);
		if (!flag)
		{
			return;
		}

		if (idList.size() <= 0)
		{
			return;
		}

		List<Integer> successList = new ArrayList<>();
		for (Integer id : idList)
		{
			flag = CommandExecutor.executorSqlCommand(RecordSlotPackHistoryCmd.NAME, id,false);
			if (flag)
			{
				successList.add(id);
			}
		}

		if (successList.size() <= 0)
		{
			return;
		}

		CommandExecutor.executorSqlCommand(RenewSlotPackSyncCmd.NAME, successList,false);
	}

	private void syncPackageOffData()
	{
		idList.clear();
		boolean flag = CommandExecutor.executorSqlCommand(FetchPacketOffByNoSyncCmd.NAME, idList,false);
		if (!flag)
		{
			return;
		}

		if (idList.size() <= 0)
		{
			return;
		}

		List<Integer> successList = new ArrayList<>();
		for (Integer id : idList)
		{
			flag = CommandExecutor.executorSqlCommand(RecordPacketOffHistoryCmd.NAME, id,false);
			if (flag)
			{
				successList.add(id);
			}
		}

		if (successList.size() <= 0)
		{
			return;
		}

		CommandExecutor.executorSqlCommand(RenewPacketOffSyncCmd.NAME, successList,false);

	}
}
